
import 'dart:convert';
import 'dart:core';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_niandaxue/config/device.dart';
import 'package:flutter_niandaxue/config/index.dart';
import 'package:flutter_niandaxue/model/base_model.dart';
import 'package:flutter_niandaxue/model/user_info.dart';
import 'package:flutter_niandaxue/pages/login_page.dart';
import 'package:flutter_niandaxue/service/http_service.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:package_info/package_info.dart';
import 'package:url_launcher/url_launcher.dart';

enum Action {
  Ok,
  Cancel
}

class SetUpPage extends StatefulWidget{

  final UserAppInfo userInfo;
  SetUpPage({Key key, @required this.userInfo}):super(key:key);

  @override
  State<StatefulWidget> createState() => new _SetUpPageState(userInfo: this.userInfo);
}

class _SetUpPageState extends State<SetUpPage>{
  final UserAppInfo userInfo;
  _SetUpPageState({this.userInfo});

  String _appName = '---';
  String _version = '---';
  String _currentNewVersion = "";
  String progress = '';
  bool isLastVersion = true;
  VersionInfo _newVersionInfo = new VersionInfo();

  @override
  void initState() {
    // 初始化版本信息
    _systemVersionInfo();
    _getCurrentNewVersion();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(KString.setUp),
        ),
      body: _buildBody(),
    );
  }

  // 构建设置
  Widget _buildBody(){
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.center,
            height: ScreenUtil().setHeight(100),
            decoration: new BoxDecoration( // 边框设置
              color: Colors.white,
              border: new Border.all(width: 1, color: Colors.white),
            ),
            child: ListTile(
              title: Text(KString.accountInfo),
              trailing: Icon(Icons.keyboard_arrow_right, color: Colors.grey, size: 40.0),
              onTap: (){
                Navigator.push(context, MaterialPageRoute(
                    builder:(context){
                      return Scaffold(
                        appBar: AppBar(),
                        body: _buildAccountInfoBody(),
                      );
                    }
                ));
              },
            ),
          ),
          // 关于念题库
          Container(
            margin: EdgeInsets.only(top: 15.0),
            alignment: Alignment.center,
            height: ScreenUtil().setHeight(100),
            decoration: new BoxDecoration( // 边框设置
              color: Colors.white,
              border: new Border.all(width: 1, color: Colors.white),
            ),
            child: ListTile(
              title: Text(KString.aboutNdx),
              trailing: Icon(Icons.keyboard_arrow_right, color: Colors.grey, size: 40.0),
              onTap: (){
                Navigator.push(context, MaterialPageRoute(
                    builder:(context){
                      return Scaffold(
                        appBar: AppBar(),
                        body: _buildAboutBody(),
                      );
                    }
                ));
              },
            ),
          ),
          // 第3部分 退出登录
          Container(
            margin: EdgeInsets.only(top: 15.0),
            alignment: Alignment.center,
            height: ScreenUtil().setHeight(100),
            decoration: new BoxDecoration( // 边框设置
              color: Colors.white,
              border: new Border.all(width: 1, color: Colors.white),
            ),
            child: ListTile(
              title: Text(KString.logout, textAlign: TextAlign.center,),
              onTap: (){
                _openAlertDialog("是否退出登录");
              },
            ),
          ),
        ],

      ),
    );
  }

  // 关于年题库
  Widget _buildAboutBody() {
    return Container(
      height: ScreenUtil().height,
      child: Column(
        children: <Widget>[
          // 1 第1部分
          Container(
            alignment: Alignment.center,
            height: ScreenUtil().setHeight(400),
            decoration: new BoxDecoration( // 边框设置
              color: Colors.white,
              border: new Border.all(width: 1, color: Colors.white),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  height: 100,
                  width: 100,
                  child:  Image.asset(KImage.logo),
                ),
                Container(
                  margin: EdgeInsets.only(top: 20.0),
                  height: 30,
                  child:  Text(_appName, style: KFont.courseTitleStyle),
                ),
                Container(
                  height: 30,
                  child:  Text(('Version ' + _version) , style: KFont.courseTitleStyle),
                ),
              ],
            ),
          ),
          // 2 第2部分 投诉与建议
          Container(
            alignment: Alignment.center,
            height: ScreenUtil().setHeight(100),
            decoration: new BoxDecoration( // 边框设置
              color: Colors.white,
              border: new Border.all(width: 1, color: Colors.white),
            ),
            child: ListTile(
              title: Text(KString.advise),
              trailing: Icon(Icons.keyboard_arrow_right, color: Colors.grey, size: 40.0),
              onTap: (){
                Navigator.push(context, MaterialPageRoute(
                    builder:(context){
                      return Scaffold(
                        appBar: AppBar(),
                        body: Center(
                          child: Text("暂未开发", style: KFont.courseTitleStyle,),
                        ),
                      );
                    }
                ));
              },
            ),
          ),
          // 3 第3部分 版本更新
          Container(
            alignment: Alignment.center,
            height: ScreenUtil().setHeight(100),
            decoration: new BoxDecoration( // 边框设置
              color: Colors.white,
              border: new Border.all(width: 1, color: Colors.white),
            ),
            child: ListTile(
              title: _buildVersionUpdateTitle(),
              trailing: Icon(Icons.keyboard_arrow_right, color: Colors.grey, size: 40.0),
              onTap: (){
                Navigator.push(context, MaterialPageRoute(
                    builder:(context){
                      return Scaffold(
                        appBar: AppBar(),
                        body: _buildVersionUpdateBody(),
                      );
                    }
                ));
              },
            ),
          ),
        ],
      ),
    );
  }

  // 构建帐号信息组件
  Widget _buildAccountInfoBody() {
    return Container(
      child: Column(
        children: <Widget>[
          // 第1部分 姓名
          Container(
            alignment: Alignment.center,
            height: ScreenUtil().setHeight(100),
            decoration: new BoxDecoration( // 边框设置
              color: Colors.white,
              border: new Border.all(width: 1, color: Colors.white),
            ),
            child: ListTile(
              title: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text("姓名", style: KFont.font18,),
                  Text(userInfo.name, style: KFont.font18,),
                ],
              ),
            ),
          ),
          // 第2部分 手机号
          Container(
            alignment: Alignment.center,
            height: ScreenUtil().setHeight(100),
            decoration: new BoxDecoration( // 边框设置
              color: Colors.white,
              border: new Border.all(width: 1, color: Colors.white),
            ),
            child: ListTile(
              title: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text("手机号", style: KFont.font18,),
                  Text(userInfo.phoneNum, style: KFont.font18,),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
  // 版本更新标题
  Widget _buildVersionUpdateTitle() {
    if(_version != _currentNewVersion && _currentNewVersion !=""){
      isLastVersion = false;
      return Container(
        child: Row(
          children: <Widget>[
            Text(KString.versionUpdate),
            SizedBox(width: 10.0),
            Icon(Icons.cloud_download, color: Colors.red,)
          ],
        ) ,
      );
    }
    return Container(
      child: Text(KString.versionUpdate) ,
    );
  }
  // 版本更新信息
  Widget _buildVersionUpdateBody() {
    String newVersion = "最新版本 " + (_currentNewVersion == null || _currentNewVersion == "" ? "--": _currentNewVersion);
    String buttonInfo = isLastVersion ? "已是最新版本了":"升级到最新版本";
    return Container(
      height: ScreenUtil().height,
      color: Colors.white,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Container(
            height: ScreenUtil().setHeight(800.0),
            decoration: new BoxDecoration( // 边框设置
              border: new Border.all(width: 1, color: Colors.white),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 30.0),
                  child: Text(newVersion, style: KFont.font18,),
                ),
                Container(
                  margin: EdgeInsets.only(left: 10.0, top: 20.0),
                  alignment: Alignment.centerLeft,
                  child: Text('本次更新：',
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 10.0, top: 10.0),
                  alignment: Alignment.centerLeft,
                  child: Text(_newVersionInfo.verExplain),
                ),
                Container(
                  margin: EdgeInsets.only(left: 10.0, top: 50.0),
                  alignment: Alignment.center,
                  child: MaterialButton(
                    color: KColor.primaryColor,
                    textColor: Colors.white,
                    minWidth: 250.0,
                    child: new Text(buttonInfo),
                    onPressed: () {
                      if(isLastVersion){
                        _showToast("已经是最新版本了");
                      }else{
                        _updateVersionUrl();
                      }
                    },
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 10.0, top: 10.0),
                  alignment: Alignment.centerLeft,
                  child: Text(progress),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  // 版本信息
  _systemVersionInfo() async{
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    _appName = packageInfo.appName;   //APP名称
    String packageName = packageInfo.packageName;   //包名
    _version = packageInfo.version; //版本名
    String buildNumber = packageInfo.buildNumber;   //版本号
  }
  // 获取系统版本信息
  _getCurrentNewVersion() async{
    var param = '/'+ KDevice.deviceType.toString();
    request_get_json('version/currentNew', formData: param).then((val){
      var data = json.decode(val.toString());
      setState(() {
        _newVersionInfo = VersionInfo.fromJson(data['data']);
        _currentNewVersion = _newVersionInfo.versionNum;
      });
    });
  }

  // 升级到最新版本, 通过浏览器下载
  _updateVersionUrl() async {
    String url = _newVersionInfo.downLoadUrl;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      _showToast("更新失败，请稍后再试");
    }
  }

  // 提示信息
  void _showToast(msg){
    Fluttertoast.showToast(
      msg: msg,
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
    );
  }
  // 退出登录
  _logout() async{
    request_post_json('userApp/logout').then((val){
      setState(() {
        removeLocal(KDevice.token_name);
      });
    });
  }

  // 打开弹框
  Future _openAlertDialog(content) async {
    final action = await showDialog(
      context: context,
      barrierDismissible: false,//// user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
//          title: Text('提示'),
          content: Text(content),
          actions: <Widget>[
            FlatButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.pop(context, Action.Cancel);
              },
            ),
            FlatButton(
              child: Text('确认'),
              onPressed: () {
                _logout();
                Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder:(context){
                  return new LoginPage();
                }), (check) => false);
              },
            ),
          ],
        );
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}